package com.ruoyi.interceptor;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

public class AuthInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 从请求头获取认证信息
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            String token = servletRequest.getServletRequest().getParameter("token");
            if (token != null && token.startsWith("Admin ")) {
                attributes.put("role", "admin");
            } else {
                attributes.put("role", "user");
            }
            System.out.println(token);
            return true;
        }
        return false;
//        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
//        String authHeader = servletRequest.getServletRequest().getParameter("token");
//        if (authHeader != null && authHeader.startsWith("Admin ")) {
//            attributes.put("role", "admin");
//        } else {
//            attributes.put("role", "user");
//        }
//        System.out.println(authHeader);
//        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                               WebSocketHandler wsHandler, Exception exception) {}
}